package com.vshop.controller.externalInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.external.deviceinfobatch.request.RequestBatchDeviceInfo;
import com.vshop.entity.external.deviceinfobatch.request.RequestBatchDeviceInfoData;
import com.vshop.entity.external.deviceinfobatch.response.*;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.newpojo.response.subResponse.common.Page;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.batchdevicerealtime.request.RequestBatchDeviceRealTime;
import com.vshop.entity.requestinterface.batchdevicerealtime.response.ResponseBatchDeviceRealTime;
import com.vshop.entity.requestinterface.batchdevicerealtime.response.ResponseBatchDeviceTradeData;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.SequenceService;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 批量获取企业下面所拥有的的设备的实时信息
 * <p>
 * 接入方可以通过调用该接口，查询所拥有的设备信息，包括设备的基本信息、设备当前订购的套餐信息等
 * <p>
 * 用于需要对接后台实时查询名下所有设备的状态的企业
 * <p>
 * 按照分页的思想前来获取，可先存到客户服务器，然后自己的app用接口获取内容
 *
 * @author lm
 * @date 2019/10/28
 */
@RestController
@Api(description = "批量获取企业所拥有的的设备的信息 ")
@Slf4j
public class BatchDeviceController {
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private PartnerInfoService partnerInfoService;

    /**
     * 直接请求网关xml接口的地址
     */
    @Value("${iot.requestURI}")
    private String requestURI;

    @CrossOrigin
    @PostMapping(value = "batchDevice", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "批量获取设备信息 ", response = ResponseBatchDeviceInfo.class)
    public String batchDevice(@ApiParam @RequestBody RequestBatchDeviceInfo request) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();

        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestBatchDeviceInfo requestPackage = JSONArray.parseObject(requestStr, RequestBatchDeviceInfo.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {

                RequestBatchDeviceInfoData requestData = requestPackage.getData();
                if (requestData == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {

                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String secret = partnerInfoService.getSecretByPartnerCode(partnerCode);
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String version = requestData.getVersion();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(version) || requestData.getTradeData() == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        Integer pageNo = requestData.getTradeData().getPageNo();
                        Integer pageSize = requestData.getTradeData().getPageSize();

                        if (pageNo == null || pageSize == null) {
                            log.info("请求报文不合法:tradeData参数不合法");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {

                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);

                            if (!requestSign.equalsIgnoreCase(sign)) {
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "The signature is wrong, please confirm the signature!");
                                return jsonString;

                            } else {

                                RequestBatchDeviceRealTime re = new RequestBatchDeviceRealTime();
                                re.setPageNo(pageNo);
                                re.setPageSize(pageSize);
                                re.setPartnerCode(partnerCode);
                                re.setSecret(secret);

                                //组装需要的json去请求报文
                                String requestInterface = JSON.toJSONString(re);
                                String url = requestURI + Constant.iot_batchDeviceRealTimeNew_2;
                                // 发送post请求，并接收返回结果
                                String returnStr = HttpUtil.httpPost(url, requestInterface);
                                ResponseBatchDeviceRealTime response = JSONArray.parseObject(returnStr, ResponseBatchDeviceRealTime.class);

                                if (response != null) {

                                    if ( Constant.RET_CODE_0000.equalsIgnoreCase(response.getRetCode())) {

                                        ResponseBatchDeviceInfoTradeData tradeData = new ResponseBatchDeviceInfoTradeData();
                                        Page page = null;
                                        List<ResponseBatchQueryDeviceInfo> deviceInfoList = new ArrayList<ResponseBatchQueryDeviceInfo>();

                                        if (response.getTradeData() != null && response.getTradeData().size() > 0 && response.getDeviceNum() > 0) {

                                            ResponseBatchQueryDeviceInfo deviceInfo = null;

                                            ResponseBatchQueryDeviceInfoPackageOrder packageOrder = null;

                                            for (ResponseBatchDeviceTradeData tr : response.getTradeData()) {

                                                if (StringUtils.isNotBlank(tr.getLifecycle()) && StringUtils.isNotBlank(tr.getDeviceId()) && tr.getPackageOrder() != null) {

                                                    packageOrder = new ResponseBatchQueryDeviceInfoPackageOrder();

                                                    if (StringUtils.isNotBlank(tr.getPackageOrder().getOrderId())) {

                                                        packageOrder.setOrderId(tr.getPackageOrder().getOrderId());
                                                        packageOrder.setPackageCode(tr.getPackageOrder().getPackageCode());
                                                        packageOrder.setPackageName(tr.getPackageOrder().getPackageName());
                                                        packageOrder.setPackageType(tr.getPackageOrder().getPackageType());
                                                        packageOrder.setOrderPeriod(tr.getPackageOrder().getOrderPeriod());

                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getBuyType())) {
                                                            packageOrder.setBuyType(tr.getPackageOrder().getBuyType());
                                                        } else {
                                                            packageOrder.setBuyType("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getFlow())) {
                                                            packageOrder.setFlow(tr.getPackageOrder().getFlow());
                                                        } else {
                                                            packageOrder.setFlow("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getUsedFlow())) {
                                                            packageOrder.setUsedFlow(tr.getPackageOrder().getUsedFlow());
                                                        } else {
                                                            packageOrder.setUsedFlow("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getFlowUseRate())) {
                                                            packageOrder.setFlowUseRate(tr.getPackageOrder().getFlowUseRate());
                                                        } else {
                                                            packageOrder.setFlowUseRate("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getOrderUsedFlow())) {
                                                            packageOrder.setOrderUsedFlow(tr.getPackageOrder().getOrderUsedFlow());
                                                        } else {
                                                            packageOrder.setOrderUsedFlow("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getOrderDate())) {
                                                            packageOrder.setOrderDate(tr.getPackageOrder().getOrderDate());
                                                        } else {
                                                            packageOrder.setOrderDate("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getActiveDate())) {
                                                            packageOrder.setActiveDate(tr.getPackageOrder().getActiveDate());
                                                        } else {
                                                            packageOrder.setActiveDate("");
                                                        }
                                                        if (StringUtils.isNotBlank(tr.getPackageOrder().getExpireDate())) {
                                                            packageOrder.setExpireDate(tr.getPackageOrder().getExpireDate());
                                                        } else {
                                                            packageOrder.setExpireDate("");
                                                        }
                                                    }

                                                }

                                                deviceInfo = new ResponseBatchQueryDeviceInfo();
                                                deviceInfo.setDeviceCode(tr.getDeviceId());
                                                deviceInfo.setOtaFlag(tr.getOtaFlag());
                                                deviceInfo.setBipFlag(tr.getBipFlag());
                                                deviceInfo.setMultiImsiFlag(tr.getMultiImsiFlag());
                                                deviceInfo.setLifecycle(tr.getLifecycle());
                                                deviceInfo.setLifecycleStartTime(tr.getLifecycleStartTime());
                                                deviceInfo.setLifecycleEndTime(tr.getLifecycleEndTime());
                                                deviceInfo.setLifecycleSlientPeriod(tr.getLifecycleSlientPeriod());
                                                deviceInfo.setLifecycleShutdownPeriod(tr.getLifecycleShutdownPeriod());
                                                deviceInfo.setPackageOrder(packageOrder);
                                                deviceInfoList.add(deviceInfo);

                                            }

                                            page = new Page();
                                            page.setCurrentPageNo(response.getPage().getCurrentPageNo());
                                            page.setPageSize(response.getPage().getPageSize());
                                            page.setTotalCount(response.getPage().getTotalCount());
                                            page.setTotalPages(response.getPage().getTotalPages());

                                            tradeData.setDeviceInfo(deviceInfoList);
                                            tradeData.setDeviceNum(response.getDeviceNum());
                                            tradeData.setPage(page);

                                            ResponseBatchDeviceInfoData data = new ResponseBatchDeviceInfoData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setRetCode("0000");
                                            data.setRetMsg("success");
                                            data.setTradeData(tradeData);

                                            ResponseBatchDeviceInfo res = new ResponseBatchDeviceInfo();
                                            res.setData(data);
                                            res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                            jsonString = JSON.toJSONString(res);
                                            //log.info("响应报文：" + jsonString);
                                            return jsonString;

                                        } else { //虽然返回的是成功，但是企业并没有设备

                                            ResponseBatchDeviceInfoData data = new ResponseBatchDeviceInfoData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setRetCode(response.getRetCode());
                                            data.setRetMsg(response.getResultInfo());
                                            data.setTradeData(tradeData);

                                            ResponseBatchDeviceInfo res = new ResponseBatchDeviceInfo();
                                            res.setData(data);
                                            res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                            jsonString = JSON.toJSONString(res);
                                            log.info("响应报文：" + jsonString);
                                            return jsonString;

                                        }

                                    } else {
                                        ResponseBatchDeviceInfoData data = new ResponseBatchDeviceInfoData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setRetCode(response.getRetCode());
                                        data.setRetMsg(response.getResultInfo());

                                        ResponseBatchDeviceInfo res = new ResponseBatchDeviceInfo();
                                        res.setData(data);
                                        res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                        jsonString = JSON.toJSONString(res);
                                        log.info("响应报文：" + jsonString);
                                        return jsonString;
                                    }


                                } else {
                                    ResponseBatchDeviceInfoData data = new ResponseBatchDeviceInfoData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setRetCode("9999");
                                    data.setRetMsg("接口响应出现异常");

                                    ResponseBatchDeviceInfo res = new ResponseBatchDeviceInfo();
                                    res.setData(data);
                                    res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                    jsonString = JSON.toJSONString(res);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;

                                }


                            }
                        }
                    }
                }
            }
        }

    }
}
